#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>

using namespace std;

class Solution {
public:
    // 494. 目标和
    // https://leetcode.cn/problems/target-sum/
    int findTargetSumWays(vector<int>& nums, int target) {
        int sum = 0;
        for (auto num : nums)
            sum += num;
        
        int aim = (sum - target) / 2;
        if (aim < 0 || (sum - target) % 2)
            return 0;
        
        int n = nums.size();
        vector<int> dp(aim+1);
        dp[0] = 1;

        for (int i = 1; i<=n; ++i)
        {
            for (int j = aim; j >= nums[i-1]; --j)
            {
                dp[j] += dp[j-nums[i-1]];
            }
        }

        return dp[aim];
    }

    // 1049. 最后一块石头的重量 II
    // https://leetcode.cn/problems/last-stone-weight-ii/
    int lastStoneWeightII(vector<int>& stones) {
        int sum = 0;
        for (auto num : stones)
            sum += num;
        int aim = sum / 2;
        int n = stones.size();
        vector<int> dp(aim + 1);
        for (int i = 1; i<=n; ++i)
        {
            for (int j = aim; j>=stones[i-1]; --j)
            {
                dp[j] = max(dp[j], stones[i-1] + dp[j-stones[i-1]]);
            }
        }

        return sum - 2*dp[aim];
    }
};